package com.ttms.web.user;
import com.google.gson.Gson;
import com.ttms.pojo.*;
import com.ttms.service.*;
import com.ttms.service.impl.*;
import com.ttms.utils.WebUtils;
import com.ttms.web.common.BaseServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
public class IndexServlet extends BaseServlet {
    PlayService playService = new PlayServiceImpl();
    ScheduleService scheduleService =new ScheduleServiceImpl();
    StudioService studioService = new StudioServiceImpl();
    SaleService saleService = new SaleServiceImpl();
    SaleItemService saleItemService = new SaleItemServiceImpl();
    SeatService seatService = new SeatServiceImpl();
    TicketService ticketService = new TicketServiceImpl();
    List<Schedule> schedules =  scheduleService.querySchedules();
    List<Play> plays = playService.queryPlays();
    List<PlayLang> playLangs = playService.queryPlayLangs();
    List<PlayType> playTypes = playService.queryPlayTypes();

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"),  Page.PAGE_SIZE);
        Page<Schedule> page = scheduleService.page(pageNo,pageSize);
        page.setUrl("/ttms/user/indexServlet?action=page");
        req.setAttribute("page",page);
        req.setAttribute("plays", plays);
        req.setAttribute("playLangs", playLangs);
        req.setAttribute("playTypes", playTypes);
        req.getRequestDispatcher("/front-end/views/user/index.jsp").forward(req,resp);
    }

    protected void chooseSeat(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int sched_id= WebUtils.parseInt(req.getParameter("sched_id") ,1);
        Schedule schedule = scheduleService.queryScheduleById(sched_id);
        Studio studio = studioService.queryStudioById(schedule.getStudio_id());
        List<StringBuffer> map = seatService.getSeatMap(sched_id,studio.getStudio_id());
        Play play = playService.queryPlayById(schedule.getPlay_id());
        req.getSession().setAttribute("studio", studio);
        req.getSession().setAttribute("studio_row", studio.getStudio_row_count());
        req.getSession().setAttribute("sched_id", sched_id);
        req.setAttribute("play", play);
        System.out.println(map);
        req.setAttribute("map", map);
        req.setAttribute("schedule",schedule);
        req.getRequestDispatcher("/front-end/views/user/chooseseat.jsp").forward(req,resp);
    }

    protected void play(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"),  Page.PAGE_SIZE);
        Page<Schedule> page = scheduleService.page(pageNo,pageSize);
        page.setUrl("/ttms/user/indexServlet?action=page");
        req.setAttribute("page",page);
        req.setAttribute("plays", plays);
        req.setAttribute("playLangs", playLangs);
        req.setAttribute("playTypes", playTypes);
        req.setAttribute("schedules", schedules);
        req.getRequestDispatcher("/front-end/views/user/hotshowing.jsp").forward(req,resp);
    }
    protected void myOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        Sale sale = saleService.querySaleByUserId(user.getId());
        List<SaleItem> saleItems = saleItemService.querSaleItemsBySaleId(sale.getSale_id());
        ArrayList<Ticket> tickets = new ArrayList<Ticket>();
        ArrayList<Seat> seats = new ArrayList<Seat>();
        for (SaleItem saleitem :saleItems) {
            Ticket ticket = ticketService.findTicketById(saleitem.getTicket_id());
            tickets.add(ticket);
            Seat seat = seatService.getSeatRowAndCol(ticket.getSeat_id());
            seats.add(seat);
        }
        req.setAttribute("plays", plays);
        req.setAttribute("schedules", schedules);
        req.setAttribute("seats", seats);
        req.setAttribute("tickets", tickets);
        req.setAttribute("saleItemList", saleItems);
        req.getRequestDispatcher("/front-end/views/user/myorder.jsp").forward(req,resp);
    }

    protected void orderDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user =(User)req.getSession().getAttribute("user");
        System.out.println(user.getUsername());
        Integer id = user.getId();
        int sched_id = WebUtils.parseInt(req.getParameter("sched_id"), 0);
        int ticket_id = WebUtils.parseInt(req.getParameter("ticket_id"), 0);
        Ticket ticket = ticketService.findTicketById(ticket_id);
        Schedule schedule = scheduleService.queryScheduleById(sched_id);
        Play play = playService.queryPlayById(schedule.getPlay_id());
        req.setAttribute("playLangs", playLangs);
        req.setAttribute("playTypes", playTypes);
        req.setAttribute("play", play);
        req.setAttribute("schedule",schedule);
        req.setAttribute("ticket",ticket);
        req.getRequestDispatcher("/front-end/views/user/orderdetail.jsp").forward(req, resp);
    }


    protected void buyTicket(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Integer studio_id = Integer.valueOf(req.getParameter("studio_id"));
    Integer user_id = Integer.valueOf(req.getParameter("user_id"));
    String arrseat = req.getParameter("arrseat");
    Integer sched_id = Integer.valueOf(req.getParameter("sched_id"));
    Schedule schedule = scheduleService.queryScheduleById(Integer.valueOf(sched_id));
    System.out.println(arrseat);
    String[] char_as=arrseat.split(",");
    BigDecimal count = new BigDecimal(char_as.length/2);
    BigDecimal price = count.multiply(schedule.getSched_ticket_price());
    Date date = new Date();
    Timestamp timeStamep = new Timestamp(date.getTime());
    System.out.println("当前时间："+date);
    Sale userSale = saleService.querySaleByUserId(user_id);
    Integer sale_id;
    if(userSale==null){
        Sale sale = new Sale(null, user_id,timeStamep,price,new BigDecimal(0),1,0);
        saleService.createSale(sale);
        sale_id = saleService.querySaleByUserId(user_id).getSale_id();
    }else{
        sale_id = userSale.getSale_id();
        userSale.setSale_payment(userSale.getSale_payment().add(price));
        saleService.update(userSale);
    }

    for (int i = 0; i < char_as.length; i+=2) {
        Seat seat = seatService.getSeatId(studio_id, Integer.valueOf(char_as[i]), Integer.valueOf(char_as[i+1]));
//        seat.setSeat_status(-1);
//        seatService.setStatus(seat);
        Ticket ticket = new Ticket(null, seat.getSeat_id(), sched_id, schedule.getSched_ticket_price(), 1,5);
        ticketService.createTicket(ticket);
        ticket = ticketService.findTicketBySeatId(sched_id,seat.getSeat_id());
        SaleItem saleItem = new SaleItem(null, ticket.getTicket_id(), sale_id,schedule.getSched_ticket_price());
        System.out.println("票的ID"+ticket.getTicket_id()+"订单ID"+sale_id);
        saleItemService.createSaleItem(saleItem);
        System.out.println("票的ID"+ticket.getTicket_id()+"订单ID"+sale_id);


    }
    Gson gson = new Gson();
    String json = gson.toJson("订票成功");
    System.out.println(json);
    resp.getWriter().write(json);
    }


    protected void refund(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        int sched_id = WebUtils.parseInt(req.getParameter("sched_id"), 0);
        int user_id = WebUtils.parseInt(req.getParameter("user_id"), 0);
        int ticket_id = WebUtils.parseInt(req.getParameter("ticket_id"), 0);
        Ticket ticket = ticketService.findTicketById(ticket_id);
        Seat seat = seatService.getSeatRowAndCol(ticket.getSeat_id());
        seat.setSeat_status(1);
        seatService.setStatus(seat);
        Sale sale = saleService.querySaleByUserId(user_id);
        BigDecimal sale_payment = sale.getSale_payment();
        sale.setSale_payment(sale_payment.subtract(ticket.getTicket_price()));
        saleService.update(sale);
        saleItemService.deleteSaleItemByTicket( ticket_id);
        ticketService.findTicketById(ticket_id);
        ticketService.deleteTicket(ticket_id);
        Gson gson = new Gson();
        String json = gson.toJson("退票成功");
        System.out.println(json);
        resp.getWriter().write(json);
    }

}
